package my.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import my.jdbc.DbConUtil;
import my.jdbc.JdbcTemplate;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import util.DataExchangeUtil;
import bean.BfJyys;
import bean.BfJyysDetail;
import bean.BfJyysJson;
import bean.JhysBean;
import bean.JhysIsOk;
import bean.JhysSyncLogsBean;
import bean.PageParamBean;
import ehcache.EhCacheManager;

@Controller
@RequestMapping("jhsy")
public class JhysToolsAction {

	private static Cache ehcache = EhCacheManager.getInstance();

	/**
	 * 进货验收首页
	 * 
	 * @param session
	 * @param ipAddress
	 * @param ckdNo
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping("index")
	@ResponseBody
	public Object indexAction(HttpSession session, String ipAddress, String ckdNo, String beginTime, String endTime) {
		List<JhysBean> jhysInfoList = new ArrayList<JhysBean>();
		if (StringUtils.isBlank(ipAddress)) {
			return jhysInfoList;
		}

		// 查询该站对应的油站编码
		selectNodeAction(ipAddress);

		String nodeNo = ehcache.get(ipAddress + "nodeno").getObjectValue().toString();

		String sql = "SELECT b.DeliveryNo deliveryNob,b.CreateTime createTimeb,b.IsDel isDelb,b.DuringSales duringSalesb,b.TranStatus tranStatusb,b.BeginTime beginTimeb,b.EndTime endTimeb,b.*,a.* FROM oss_acceptance_odRegister a LEFT JOIN oss_acceptance_odRegisterInfo b on a.ManualNo = b.ManualNo where 1=1 ";
		List<Object> fields = new ArrayList<Object>();
		if (StringUtils.isNotBlank(ckdNo)) {
			sql += " and a.ManualNo = ? ";
			fields.add(ckdNo);
		}
		if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
			sql += " and DATE_FORMAT(b.EndTime,'%Y-%m-%d') >= ? and DATE_FORMAT(b.EndTime,'%Y-%m-%d') <= ? ORDER BY b.EndTime DESC ";
			fields.add(beginTime);
			fields.add(endTime);
		}
		jhysInfoList = JdbcTemplate.queryListInfoByFields(DbConUtil.getGsmappCon(ipAddress), sql, JhysBean.class, fields, ipAddress);

		// 将该油站下的所有进货验收缓存
		List<Object> fields1 = new ArrayList<Object>();
		fields1.add(nodeNo);
		List<JhysIsOk> jhysIsOKList = JdbcTemplate.queryListInfoByFields(DbConUtil.get162ptCon(), "SELECT nodeno,deliveryno FROM BF_JYYS WHERE etime is NOT NULL AND nodeno = ? ",
				JhysIsOk.class, fields1, DbConUtil.TYPE_NAME_162PT);
		List<JhysIsOk> jhysIsOKListFilter = JdbcTemplate.queryListInfoByFields(DbConUtil.get162ptCon(),
				"SELECT nodeno,deliveryno FROM BF_JYYS_FILTER WHERE etime is NOT NULL AND nodeno = ? ", JhysIsOk.class, fields1, DbConUtil.TYPE_NAME_162PT);

		List<String> deliverynoList = new ArrayList<String>();
		List<String> deliverynoListFilter = new ArrayList<String>();
		for (JhysIsOk jhysIsOk : jhysIsOKList) {
			deliverynoList.add(jhysIsOk.getDeliveryno());
		}

		for (JhysIsOk jhysIsOkFilter : jhysIsOKListFilter) {
			deliverynoListFilter.add(jhysIsOkFilter.getDeliveryno());
		}

		for (JhysBean jhysobject : jhysInfoList) {
			if (deliverynoList.contains(jhysobject.getDeliveryNo())) {
				jhysobject.setIsDoneJhys(1);
			} else if (deliverynoListFilter.contains(jhysobject.getDeliveryNo())) {
				jhysobject.setIsDoneJhys(2);
			} else {
				jhysobject.setIsDoneJhys(0);
			}
		}

		ehcache.put(new Element(ipAddress, jhysInfoList));
		return jhysInfoList;
	}

	/**
	 * 将数据上传到中转站
	 * 
	 * @param ipAddress
	 * @param deliveryNos
	 * @param jhysIsOKdeliveryNoList
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("upload")
	@ResponseBody
	public Object uploadAction(String ipAddress, List<String> deliveryNos, List<String> jhysIsOKdeliveryNoList) {
		// JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {
		// "yyyy-MM-dd HH:mm:ss" }));
		final List<JhysBean> JhysBeanlist = (List<JhysBean>) ehcache.get(ipAddress).getObjectValue();
		String inserttime = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");

		String sql = "INSERT INTO oss_acceptance_odRegister VALUES ([oilNo], [shift], [manualNo], [deliveryNo], [dischargeLoss], [dischargeLossV20], [dischargeRate], [dischargeRateV20], [planL], [realReceiveL], [heightEmpey], [heightTotal], [heightWater], [cubageTable], [plumbunBankOperator], [calculateOperator], [backBankNo], [canTruckTemp], [isFullDose], [serviceLevel], [createTime], [isDel], [realGetLV20], [realGetL], [duringSales], [tranStatus], [inStationTime], [indemnityLoss], [beginTime], [endTime],'"
				+ inserttime + "')";
		String sqlInfo = "INSERT INTO oss_acceptance_odRegisterInfo VALUES ([oilNo], [shift], [manualNo], [deliveryNo], [oilCan], [beginTimeb], [endTimeb], [dischargeL], [beginOilHeight], [beginOilL], [beginV20L], [beginTemperature], [endOilHeight], [endOilL], [endV20L], [endTemperature], [stableBeginTime], [stableEndTime], [createTimeb], [isDelb], [enterType], [duringSalesb], [tranStatusb], [forceCancelStable], [isBeforeStable], [beginWaterHeight], [endWaterHeight], [canVersion],'"
				+ inserttime + "')";

		List<String> deliveryNoList = new ArrayList<String>();

		// 将数据上传到中转表里面
		for (JhysBean jhysBean : JhysBeanlist) {
			if (!deliveryNos.contains(jhysBean.getDeliveryNo()) || jhysIsOKdeliveryNoList.contains(jhysBean.getDeliveryNo())) {
				continue;
			}
			if (!deliveryNoList.contains(jhysBean.getDeliveryNo())) {
				JdbcTemplate.insertByBean(DbConUtil.get162testCon(), sql, jhysBean, DbConUtil.TYPE_NAME_162TEST);
			}
			if (StringUtils.isNotBlank(jhysBean.getDeliveryNob())) {
				JdbcTemplate.insertByBean(DbConUtil.get162testCon(), sqlInfo, jhysBean, DbConUtil.TYPE_NAME_162TEST);
			}
			deliveryNoList.add(jhysBean.getDeliveryNo());
		}

		return true;
	}

	/**
	 * 同步并上传
	 * 
	 * @param ipAddress
	 * @param deliveryNos
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("sysnc")
	@ResponseBody
	public String sysncAndUploadAction(String ipAddress, String deliveryNos) {

		List<String> deliveryNoList = (List<String>) JSONArray.toCollection(JSONArray.fromObject(deliveryNos), String.class);

		// 判断这张单是否已经完成进货验收

		String sql = "SELECT nodeno,deliveryno FROM BF_JYYS WHERE etime is NOT NULL  AND nodeno = ? ";
		List<Object> fields = new ArrayList<Object>();
		fields.add(ehcache.get(ipAddress + "nodeno").getObjectValue().toString());
		List<JhysIsOk> jhysisOklist = JdbcTemplate.queryListInfoByFields(DbConUtil.get162ptCon(), sql, JhysIsOk.class, fields, DbConUtil.TYPE_NAME_162PT);
		List<String> jhysIsOKdeliveryNoList = new ArrayList<String>();
		for (JhysIsOk isok : jhysisOklist) {
			jhysIsOKdeliveryNoList.add(isok.getDeliveryno());
		}

		// 上传到中转站
		uploadAction(ipAddress, deliveryNoList, jhysIsOKdeliveryNoList);

		// JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {
		// "yyyy-MM-dd HH:mm:ss" }));
		final List<JhysBean> JhysBeanlist = (List<JhysBean>) ehcache.get(ipAddress).getObjectValue();
		List<String> deliveryNoList1 = new ArrayList<String>();
		final List<BfJyysJson> jhysListJson = new ArrayList<BfJyysJson>();
		// 组织json数据
		for (JhysBean jhysBean : JhysBeanlist) {
			if (!deliveryNoList.contains(jhysBean.getDeliveryNo()) || jhysIsOKdeliveryNoList.contains(jhysBean.getDeliveryNo())
					|| deliveryNoList1.contains(jhysBean.getDeliveryNo())) {
				continue;
			}

			BfJyysJson bfjson = new BfJyysJson();
			BfJyys jhys = new BfJyys();
			jhys.setNodeno(ehcache.get(ipAddress + "sys_nodeno").getObjectValue().toString());
			jhys.setDeliveryno(jhysBean.getDeliveryNo());
			jhys.setManualno(jhysBean.getManualNo());
			jhys.setOilno(jhysBean.getOilNo());
			jhys.setDischargeloss(jhysBean.getDischargeLoss());
			jhys.setDischargelossv20(jhysBean.getDischargeLossV20());
			jhys.setDischargerate(jhysBean.getDischargeRate());
			jhys.setDischargeratev20(jhysBean.getDischargeRateV20());
			jhys.setPlanl(jhysBean.getPlanL());
			jhys.setRealreceivel(jhysBean.getRealReceiveL());
			jhys.setHeightempey(jhysBean.getHeightEmpey());
			jhys.setHeighttotal(jhysBean.getHeightTotal());
			jhys.setPlumbunbankoperator(jhysBean.getPlumbunBankOperator());
			jhys.setCalculateoperator(jhysBean.getCalculateOperator());
			jhys.setBackbankno(jhysBean.getBackBankNo());
			jhys.setCantrucktemp(jhysBean.getCanTruckTemp());
			jhys.setRealgetl(jhysBean.getRealGetL());
			jhys.setRealgetlv20(jhysBean.getRealGetLV20());
			jhys.setDuringsales(jhysBean.getDuringSales());
			jhys.setBegintime(jhysBean.getBeginTime());
			jhys.setEndtime(jhysBean.getEndTime());
			jhys.setIndemnityloss(jhysBean.getIndemnityLoss());
			jhys.setInstationtime(jhysBean.getInStationTime());
			jhys.setShift(jhysBean.getShift());

			bfjson.setOdRegister(jhys);

			List<BfJyysDetail> jhysDetailList = new ArrayList<BfJyysDetail>();

			for (JhysBean jhysBean1 : JhysBeanlist) {
				if (jhysBean.getManualNo().equals(jhysBean1.getDeliveryNob())) {
					BfJyysDetail jhysDetail = new BfJyysDetail();
					jhysDetail.setDeliveryno(jhysBean1.getDeliveryNo());
					jhysDetail.setManualno(jhysBean1.getManualNo());
					jhysDetail.setOilcan(jhysBean1.getOilCan() + "");
					jhysDetail.setShift(jhysBean1.getShift());
					jhysDetail.setBegintime(jhysBean1.getBeginTimeb());
					jhysDetail.setEndtime(jhysBean1.getEndTimeb());
					jhysDetail.setDischargel(jhysBean1.getDischargeL());
					jhysDetail.setBeginoilheight(jhysBean1.getBeginOilHeight());
					jhysDetail.setBeginwaterheight(jhysBean1.getBeginWaterHeight());
					jhysDetail.setBeginoill(jhysBean1.getBeginOilL());
					jhysDetail.setBeginv20l(jhysBean1.getBeginV20L());
					jhysDetail.setBegintemperature(jhysBean1.getBeginTemperature());
					jhysDetail.setEndoilheight(jhysBean1.getEndOilHeight());
					jhysDetail.setEndwaterheight(jhysBean1.getEndWaterHeight());
					jhysDetail.setEndoill(jhysBean1.getEndOilL());
					jhysDetail.setEndv20l(jhysBean1.getEndV20L());
					jhysDetail.setEndtemperature(jhysBean1.getEndTemperature());
					jhysDetail.setBeginentertype(jhysBean1.getEnterType() == null ? 0 : jhysBean1.getEnterType());
					jhysDetail.setEndentertype(jhysBean1.getEnterType() == null ? 0 : jhysBean1.getEnterType());
					jhysDetail.setDuringsales(jhysBean1.getDuringSalesb());
					jhysDetail.setForcecancelstable(jhysBean1.getForceCancelStable() == null ? 0 : jhysBean1.getForceCancelStable());
					jhysDetail.setCanversion(jhysBean1.getCanVersion());
					jhysDetailList.add(jhysDetail);
				}
			}

			bfjson.setRegisterInfos(jhysDetailList);
			deliveryNoList1.add(jhysBean.getDeliveryNo());
			jhysListJson.add(bfjson);
		}

		new Thread() {
			@Override
			public void run() {
				DataExchangeUtil.sendJhysData(jhysListJson, "JhysToolsAction");
			}
		}.start();

		return "ok";
	}

	@RequestMapping("nodeInfo")
	@ResponseBody
	public Object selectNodeAction(String ipAddress) {
		Map<String, String> nodeMap = new HashMap<String, String>();
		if (StringUtils.isBlank(ipAddress)) {
			return nodeMap;
		}
		if (ehcache.get(ipAddress + "nodeno") == null || ehcache.get(ipAddress + "nodeName") == null) {
			// 查询油站编码
			Object[] departmentInfo = JdbcTemplate.queryFieldInfoByBean(DbConUtil.getGsmappCon(ipAddress), "SELECT * FROM oss_sysmanage_department", null, ipAddress);
			String nodeno = departmentInfo[0].toString();
			String nodeName = departmentInfo[3].toString();
			// 油站代码转换
			String stationCodeSql = " SELECT * FROM SH_STATION WHERE control_station_code = '" + nodeno + "' ";
			Object[] stationInfo = JdbcTemplate.queryFieldInfoByFields(DbConUtil.get162ptCon(), stationCodeSql, null, DbConUtil.TYPE_NAME_162PT);
			ehcache.put(new Element(ipAddress + "nodeno", stationInfo == null ? nodeno : stationInfo[0]));
			ehcache.put(new Element(ipAddress + "nodeName", nodeName));
			// 上传进货验收数据时不需要对编码进行转换
			ehcache.put(new Element(ipAddress + "sys_nodeno", nodeno));
		}
		nodeMap.put("nodeno", ehcache.get(ipAddress + "nodeno").getObjectValue().toString());
		nodeMap.put("sys_nodeno", ehcache.get(ipAddress + "sys_nodeno").getObjectValue().toString());
		nodeMap.put("nodeName", ehcache.get(ipAddress + "nodeName").getObjectValue().toString());

		return nodeMap;
	}

	@RequestMapping("synclogs")
	@ResponseBody
	public Object syncLogsAction(String ckdNo, String beginTime, String endTime, String nodeno, PageParamBean page, String selectType) {
		Map<String, Object> pageMap = new HashMap<String, Object>();
		if (StringUtils.isBlank(selectType)) {
			pageMap.put("total", 0);
			pageMap.put("rows", new ArrayList<JhysSyncLogsBean>());
			return pageMap;
		}
		String countSql = " SELECT COUNT(1) FROM jhys_sync_logs WHERE 1=1 ";
		String sql = " SELECT * FROM ( SELECT row_number() OVER (ORDER BY dated DESC) rowId,message,dated FROM jhys_sync_logs WHERE 1=1 ";
		if (StringUtils.isNotBlank(ckdNo)) {
			sql += " AND MESSAGE LIKE '%" + ckdNo + "%' ";
			countSql += " AND MESSAGE LIKE '%" + ckdNo + "%' ";
		}
		if (StringUtils.isNotBlank(nodeno)) {
			sql += " AND MESSAGE LIKE '%" + nodeno + "%' ";
			countSql += " AND MESSAGE LIKE '%" + nodeno + "%' ";
		}

		if (StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime)) {
			sql += " AND CONVERT(VARCHAR, DATED, 23) >= '" + beginTime + "' AND CONVERT(VARCHAR, DATED, 23) <= '" + endTime + "' ";
			countSql += " AND CONVERT(VARCHAR, DATED, 23) >= '" + beginTime + "' AND CONVERT(VARCHAR, DATED, 23) <= '" + endTime + "' ";
		}
		sql += " ) AS t WHERE t.rowId BETWEEN " + (page.getOffset() + 1) + "  AND " + page.getPage() * page.getPagesize() + " ";
		List<JhysSyncLogsBean> jhysLogList = JdbcTemplate.queryListInfoByFields(DbConUtil.get162testCon(), sql, JhysSyncLogsBean.class, null, DbConUtil.TYPE_NAME_162TEST);
		Object[] count = JdbcTemplate.queryFieldInfoByFields(DbConUtil.get162testCon(), countSql, null, DbConUtil.TYPE_NAME_162TEST);
		pageMap.put("total", count[0]);
		pageMap.put("rows", jhysLogList);
		return pageMap;
	}

}
